/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ourPrint.java
 *
 * Created on 22-gen-2009, 12.38.58
 */

package our.gui;

import java.awt.Cursor;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author keysman
 */
public abstract class ourPrint extends javax.swing.JDialog implements ourInterfacePrint {
    private Object[][] _OBJFIELDS = null;

    private int ID_LSTFILTRIFLDS = 0; // Id selezionato (filtro)
    private int ID_LSTFILTRICOND = 0; // Id selezionato (condizione)
    private int ID_IDTABLE       = -1; // Tabella riepilogativa (per default non seleziono nulla)
    private int ID_LSTORD        = 0; // Tabella odinamento
    private int ID_LSTORDSEL     = -1; // Tabella campi 'selezionati' per l'ordinamento (per default nn ci sono campi)
    private int ID_LSTOP         = 0; // Id Operatiore (Per default è l'AND)

    private String _TABLENAME;
    private String _JRXML;

   
    /** Creates new form ourPrint */
    public ourPrint(java.awt.Frame parent, boolean modal, String strCaption) {
        super(parent, modal);
        initComponents();
        // Per default imposto le dimensioni della finestra a 400x300
        int WIN_HEIGHT = 490;
        int WIN_WIDTH  = 450;
        java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
        java.awt.Dimension screenSize = tk.getScreenSize();
        int iScrH = screenSize.height;
        int iScrW = screenSize.width;
        setBounds( (iScrW - WIN_WIDTH) / 2,
                   (iScrH - WIN_HEIGHT) / 2,
                   WIN_WIDTH,
                   WIN_HEIGHT);
        panelToolbar.setSize(WIN_WIDTH, 36);
        setTitle("Stampa " + strCaption);

        // Personalizzo il gestore degli eventi
        CustomEvent customEvent = new CustomEvent();
        Action ESC   = new FXAction("ESC", customEvent);   // Chiudi la maschera
        Action UP    = new FXAction("UP", customEvent);    // Sposta il fuoco sull'oggetto precedente
        Action DOWN  = new FXAction("DOWN", customEvent); // Sposta il fuoco sull'oggetto successivo
        Action f1    = new FXAction("F1", customEvent);   // Anteprima
        Action f2    = new FXAction("F2", customEvent);   // Stampa
        Action f3    = new FXAction("F3", customEvent);   // Excel
        Action f4    = new FXAction("F4", customEvent);   // PDF
        Action f5    = new FXAction("F5", customEvent);   // CSV
        Action f6    = new FXAction("F6", customEvent);   // HTML
        Action f7    = new FXAction("F7", customEvent);   // RTF

        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "UP");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "DOWN");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false), "DOWN");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "DOWN");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK, false), "UP");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "ESC");

        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, false), "F1");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, false), "F2");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, false), "F3");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0, false), "F4");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0, false), "F5");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0, false), "F6");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0, false), "F7");

        getRootPane().getActionMap().put("UP", UP);
        getRootPane().getActionMap().put("DOWN", DOWN);
        getRootPane().getActionMap().put("ESC", ESC);
        getRootPane().getActionMap().put("F1", f1);
        getRootPane().getActionMap().put("F2", f2);
        getRootPane().getActionMap().put("F3", f3);
        getRootPane().getActionMap().put("F4", f4);
        getRootPane().getActionMap().put("F5", f5);
        getRootPane().getActionMap().put("F6", f6);
        getRootPane().getActionMap().put("F7", f7);

        // Imposto l'icona del programma
        ImageIcon icon = new ImageIcon(this.getClass().getResource("/our/gui/img/mainicon.png"));
        setIconImage(icon.getImage());

        txtFiltro.setEnabled(true);
        txtMaxRecord.setEnabled(true);
    }

    private Object[] USE_CUSTOM_MODEL(String strButton) {
        JasperPrint jprint = createSimplePrintReport(_JRXML, "select * from " + _TABLENAME);
        if(jprint!=null) return new Object[] { "", jprint };
        return null;

    }

    protected JasperPrint createSimplePrintReport(String strJrxmlFilename, String strSelect)
    {
        InputStream is = null;
        BufferedReader br = null;
        BufferedWriter out = null;
        JasperPrint jprint = null;
        String line;
        try {
            // Esporto checked.png
            File fTmpCheck = File.createTempFile("checked", ".png");
            InputStream inb = new BufferedInputStream(getClass().getResourceAsStream("/our/gui/img/checked.png"));
            OutputStream outb = new BufferedOutputStream(new FileOutputStream(fTmpCheck));
            byte[] buffer = new byte[2048];
            for(;;)
            {
                int nBytes = inb.read(buffer);
                if(nBytes<=0) break;
                outb.write(buffer, 0, nBytes);
            }
            outb.flush();
            outb.close();
            inb.close();
            
            // Esporto unchecked.png
            File fTmpUnCheck = File.createTempFile("unchecked", ".png");
            inb = new BufferedInputStream(getClass().getResourceAsStream("/our/gui/img/unchecked.png"));
            outb = new BufferedOutputStream(new FileOutputStream(fTmpUnCheck));
            buffer = new byte[2048];
            for(;;)
            {
                int nBytes = inb.read(buffer);
                if(nBytes<=0) break;
                outb.write(buffer, 0, nBytes);
            }
            outb.flush();
            outb.close();
            inb.close();
            
            // Creo un file temporaneo per il jrxml
            File fTmp = File.createTempFile("printmodel", ".jrxml");
            out = new BufferedWriter(new FileWriter(fTmp));
            is = this.getClass().getResourceAsStream(_JRXML);
            br = new BufferedReader(new InputStreamReader(is));
            while(null!=(line=br.readLine()))
            {
                //if(line.indexOf("${QUERY}")>=0)
                if(line.indexOf("<queryString>")>=0)
                {
                    // Creo la linea che contiene la query
                    String strQuery = buildQuery();
                    if(strSelect.indexOf("WHERE")>=0)
                    {
                        strQuery = strSelect + " AND " + strQuery.substring(strQuery.indexOf("WHERE") + 5);
                    } else {
                        strQuery = strSelect + " " + strQuery;
                    }
                    line = "<queryString><![CDATA[" + strQuery + "]]></queryString>\n";
                }
                out.write(line + "\n");
            }
            is.close();
            out.close();

            Map parameters = new HashMap();
            parameters.put("CHECK", fTmpCheck.getAbsolutePath());
            parameters.put("UNCHECK", fTmpUnCheck.getAbsolutePath());
            JasperReport jreport = JasperCompileManager.compileReport(fTmp.getAbsolutePath()); // Creo il report
            jprint = JasperFillManager.fillReport(jreport, parameters, our.gui.utils.connection);//our.gui.utils.sqlMap.getCurrentConnection());

            fTmpCheck.delete();
            fTmpUnCheck.delete();
            fTmp.delete();
        } catch(Exception e) {
            javax.swing.JOptionPane.showMessageDialog(this, e, "ERRORE", javax.swing.JOptionPane.ERROR_MESSAGE);
            our.gui.utils.logger.log(Level.SEVERE, e.toString());
        } finally {
            if(jprint==null) our.gui.utils.MessageBox("Si è verificato un errore in fase di generazione del report!", JOptionPane.ERROR_MESSAGE);
            return jprint;
        }
    }

    /**
     * Memorizza i dati necessari alla creazione della maschera di stampa
     * @param objFields Un array di array di tre elementi { CAMPO, CAMPO(MYSQL), TIPO(NUMERICO/STRINGA/DATA) }
     * @param _TABLENAME   Il nome della tabella
     */
    public void initialize(Object[][] objFields, String _TABLENAME, String _JRXMLFILE)
    {
        this._TABLENAME = _TABLENAME;
        this._JRXML = _JRXMLFILE;
        _OBJFIELDS = objFields;
        DefaultListModel model = new DefaultListModel();
        DefaultListModel modelSort = new DefaultListModel();
        for(int i=0; i<objFields.length; i++)
        {
            Object objTmp[] = objFields[i];
            model.add(i, objTmp[0]);
            modelSort.add(i, objTmp[0]);
        }
        lstFiltriFlds.setModel(model);
        lstFiltriFlds.setSelectedIndex(0);
        lstOrdinaFlds.setModel(modelSort);
        //lstOrdinaFlds.setSelectedIndex(0);
        lstFiltriFlds.requestFocus();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelToolbar = new javax.swing.JPanel();
        butPrinter = new our.gui.ourButton();
        butExcel = new our.gui.ourButton();
        butPDF = new our.gui.ourButton();
        butPreview = new our.gui.ourButton();
        butCsv = new our.gui.ourButton();
        butHTML = new our.gui.ourButton();
        butRTF = new our.gui.ourButton();
        pnlFiltri = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstFiltriFlds = new our.gui.ourList();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstFiltriCond = new our.gui.ourList();
        jScrollPane4 = new javax.swing.JScrollPane();
        tblFiltri = new our.gui.ourTable();
        txtFiltro = new our.gui.ourTextField(10, our.gui.ourTextField.TYPE_NUMERIC, false);
        lbl1 = new our.gui.ourLabel();
        lbl2 = new our.gui.ourLabel();
        pnlOperatore = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        lstOp = new our.gui.ourList();
        pnlOrdinamento = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstOrdinaFlds = new our.gui.ourList();
        jScrollPane5 = new javax.swing.JScrollPane();
        tblOrdina = new our.gui.ourTable();
        jPanel1 = new javax.swing.JPanel();
        txtMaxRecord = new our.gui.ourTextField(3, our.gui.ourTextField.TYPE_CODNUM, false);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(null);

        panelToolbar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        panelToolbar.setFocusable(false);
        panelToolbar.setLayout(null);

        butPrinter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/toolbar13.gif"))); // NOI18N
        butPrinter.setToolTipText("Stampa documento (F2)");
        butPrinter.setFocusable(false);
        butPrinter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butPrinterMouseClicked(evt);
            }
        });
        panelToolbar.add(butPrinter);
        butPrinter.setBounds(40, 5, 26, 26);

        butExcel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/excel.png"))); // NOI18N
        butExcel.setToolTipText("Esporta in formato Excel (F3)");
        butExcel.setFocusable(false);
        butExcel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butExcelMouseClicked(evt);
            }
        });
        panelToolbar.add(butExcel);
        butExcel.setBounds(70, 5, 26, 26);

        butPDF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/pdf.png"))); // NOI18N
        butPDF.setToolTipText("Esporta PDF (F4)");
        butPDF.setFocusable(false);
        butPDF.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butPDFMouseClicked(evt);
            }
        });
        panelToolbar.add(butPDF);
        butPDF.setBounds(100, 5, 26, 26);

        butPreview.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/preview.png"))); // NOI18N
        butPreview.setToolTipText("Anteprima di stampa (F1)");
        butPreview.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butPreviewMouseClicked(evt);
            }
        });
        panelToolbar.add(butPreview);
        butPreview.setBounds(10, 5, 26, 26);

        butCsv.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/csv.png"))); // NOI18N
        butCsv.setToolTipText("Esporta in CSV (F5)");
        butCsv.setFocusable(false);
        butCsv.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butCsvMouseClicked(evt);
            }
        });
        panelToolbar.add(butCsv);
        butCsv.setBounds(130, 5, 26, 26);

        butHTML.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/html.gif"))); // NOI18N
        butHTML.setToolTipText("Esporta come file HTML (F6)");
        butHTML.setFocusable(false);
        butHTML.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butHTMLMouseClicked(evt);
            }
        });
        panelToolbar.add(butHTML);
        butHTML.setBounds(160, 5, 26, 26);

        butRTF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/our/gui/img/rtf.png"))); // NOI18N
        butRTF.setToolTipText("Esporta in formato RTF (F7)");
        butRTF.setEnabled(false);
        butRTF.setFocusable(false);
        butRTF.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butRTFMouseClicked(evt);
            }
        });
        panelToolbar.add(butRTF);
        butRTF.setBounds(190, 5, 26, 26);

        getContentPane().add(panelToolbar);
        panelToolbar.setBounds(0, 0, 430, 36);

        pnlFiltri.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Filtri", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 0, 13), java.awt.Color.blue)); // NOI18N
        pnlFiltri.setFocusable(false);
        pnlFiltri.setLayout(null);

        jScrollPane1.setFocusable(false);

        lstFiltriFlds.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstFiltriFlds.setNextFocusableComponent(lstFiltriCond);
        lstFiltriFlds.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstFiltriFldsMouseClicked(evt);
            }
        });
        lstFiltriFlds.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstFiltriFldsValueChanged(evt);
            }
        });
        lstFiltriFlds.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                lstFiltriFldsFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                lstFiltriFldsFocusLost(evt);
            }
        });
        jScrollPane1.setViewportView(lstFiltriFlds);

        pnlFiltri.add(jScrollPane1);
        jScrollPane1.setBounds(10, 20, 130, 110);

        jScrollPane3.setFocusable(false);

        lstFiltriCond.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstFiltriCond.setNextFocusableComponent(txtFiltro);
        lstFiltriCond.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstFiltriCondMouseClicked(evt);
            }
        });
        lstFiltriCond.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                lstFiltriCondFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                lstFiltriCondFocusLost(evt);
            }
        });
        jScrollPane3.setViewportView(lstFiltriCond);

        pnlFiltri.add(jScrollPane3);
        jScrollPane3.setBounds(150, 20, 100, 110);

        jScrollPane4.setFocusable(false);

        tblFiltri.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CAMPO", "CONDIZIONE", "VALORE", "OPERATORE"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblFiltri.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblFiltriMouseClicked(evt);
            }
        });
        tblFiltri.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                tblFiltriFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                tblFiltriFocusLost(evt);
            }
        });
        tblFiltri.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblFiltriKeyPressed(evt);
            }
        });
        jScrollPane4.setViewportView(tblFiltri);

        pnlFiltri.add(jScrollPane4);
        jScrollPane4.setBounds(10, 170, 400, 80);

        txtFiltro.setNextFocusableComponent(lstOp);
        txtFiltro.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtFiltroFocusGained(evt);
            }
        });
        txtFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtFiltroKeyPressed(evt);
            }
        });
        pnlFiltri.add(txtFiltro);
        txtFiltro.setBounds(260, 20, 150, 20);

        lbl1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        pnlFiltri.add(lbl1);
        lbl1.setBounds(10, 140, 130, 20);

        lbl2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlFiltri.add(lbl2);
        lbl2.setBounds(150, 140, 100, 20);

        pnlOperatore.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Operatore", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 0, 13), java.awt.Color.blue)); // NOI18N
        pnlOperatore.setOpaque(false);
        pnlOperatore.setLayout(null);
        pnlFiltri.add(pnlOperatore);
        pnlOperatore.setBounds(260, 60, 150, 70);

        lstOp.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "AND", "OR" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstOp.setNextFocusableComponent(tblFiltri);
        lstOp.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                lstOpFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                lstOpFocusLost(evt);
            }
        });
        lstOp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                lstOpKeyPressed(evt);
            }
        });
        jScrollPane6.setViewportView(lstOp);

        pnlFiltri.add(jScrollPane6);
        jScrollPane6.setBounds(270, 80, 130, 40);

        getContentPane().add(pnlFiltri);
        pnlFiltri.setBounds(10, 40, 420, 260);

        pnlOrdinamento.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ordinamento", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 0, 13), java.awt.Color.blue)); // NOI18N
        pnlOrdinamento.setFocusable(false);
        pnlOrdinamento.setLayout(null);

        lstOrdinaFlds.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstOrdinaFlds.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstOrdinaFldsMouseClicked(evt);
            }
        });
        lstOrdinaFlds.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                lstOrdinaFldsFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                lstOrdinaFldsFocusLost(evt);
            }
        });
        lstOrdinaFlds.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                lstOrdinaFldsKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(lstOrdinaFlds);

        pnlOrdinamento.add(jScrollPane2);
        jScrollPane2.setBounds(10, 20, 130, 120);

        tblOrdina.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CAMPO"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblOrdina.setNextFocusableComponent(txtMaxRecord);
        tblOrdina.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblOrdinaMouseClicked(evt);
            }
        });
        tblOrdina.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                tblOrdinaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                tblOrdinaFocusLost(evt);
            }
        });
        tblOrdina.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblOrdinaKeyPressed(evt);
            }
        });
        jScrollPane5.setViewportView(tblOrdina);

        pnlOrdinamento.add(jScrollPane5);
        jScrollPane5.setBounds(150, 20, 130, 120);

        getContentPane().add(pnlOrdinamento);
        pnlOrdinamento.setBounds(10, 300, 290, 150);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Max. Record", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 0, 13), java.awt.Color.blue)); // NOI18N
        jPanel1.setLayout(null);

        txtMaxRecord.setToolTipText("Limita il numero di record del risultato");
        txtMaxRecord.setNextFocusableComponent(lstFiltriFlds);
        jPanel1.add(txtMaxRecord);
        txtMaxRecord.setBounds(10, 26, 110, 20);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(300, 300, 130, 60);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void lstFiltriFldsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstFiltriFldsValueChanged
        // TODO add your handling code here:
        try {
            int iType = (java.lang.Integer)_OBJFIELDS[lstFiltriFlds.getSelectedIndex()][2]; // Leggo il tipo di oggetto
            DefaultListModel model = new DefaultListModel();
            if( (iType!=our.gui.ourTextField.TYPE_NUMERIC) &&
                (iType!=our.gui.ourTextField.TYPE_CODNUM)  &&
                (iType!=our.gui.ourTextField.TYPE_BOOLEAN)  &&
                (iType!=our.gui.ourTextField.TYPE_DATA)  &&
                (iType!=our.gui.ourTextField.TYPE_ALFANUM) )
            {
                System.out.println("Hai specificato un tipo non valido.\nI tipi riconosciuti sono TYPE_NUMERIC, TYPE_CODNUM, TYPE_DATA o TYPE_ALFANUM.\n");
                System.exit(1);
            }
            if( (iType == our.gui.ourTextField.TYPE_NUMERIC) || 
                (iType == our.gui.ourTextField.TYPE_DATA)  ||
                (iType == our.gui.ourTextField.TYPE_CODNUM) )
            {
                model.add(0, ">");
                model.add(1, ">=");
                model.add(2, "<");
                model.add(3, "<=");
                model.add(4, "=");
                model.add(5, "<>");
            } else if(iType == our.gui.ourTextField.TYPE_BOOLEAN) {
                model.add(0, "=");
            } else {
                model.add(0, "Inizia con");
                model.add(1, "Finisce in");
                model.add(2, "Contiene");
                model.add(3, "Uguale a");
            }
            lstFiltriCond.setModel(model);
            //lstFiltriCond.setSelectedIndex(0);
        } catch(java.lang.ArrayIndexOutOfBoundsException aiobe) { }
    }//GEN-LAST:event_lstFiltriFldsValueChanged

    private void txtFiltroFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFiltroFocusGained
        // TODO add your handling code here:
        txtFiltro.setText("");
        int iType = (java.lang.Integer)_OBJFIELDS[ID_LSTFILTRIFLDS][2]; // Leggo il tipo di oggetto
            if( (iType == our.gui.ourTextField.TYPE_NUMERIC) || (iType == our.gui.ourTextField.TYPE_CODNUM) )
            {
                txtFiltro.setCharsInputAllowed(our.gui.ourTextField.TYPE_NUMERIC);
            } else if(iType == our.gui.ourTextField.TYPE_BOOLEAN) {
                txtFiltro.setCharsInputAllowed(our.gui.ourTextField.TYPE_BOOLEAN);
            } else {
                txtFiltro.setCharsInputAllowed(our.gui.ourTextField.TYPE_ALFANUM);
            }
    }//GEN-LAST:event_txtFiltroFocusGained

    private void txtFiltroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFiltroKeyPressed
        // TODO add your handling code here:
        int iType = ((our.gui.ourTextField)txtFiltro).getCharsInputAllowed();//==ourTextField.TYPE_NUMERIC
        if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_COMMA) && (iType==ourTextField.TYPE_NUMERIC) )
        {
            evt.consume();
            return;
        }
        /*if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) && (!txtFiltro.getText().isEmpty()) )
        {
            int iType = (java.lang.Integer)_OBJFIELDS[ID_LSTFILTRIFLDS][2];
            String strValue = txtFiltro.getText();
            if(iType==our.gui.ourTextField.TYPE_DATA)
            {
                strValue = our.gui.utils.isValidDate(strValue);
                if(strValue==null)
                {
                    our.gui.utils.MessageBox(14, -1);
                    return;
                }
                strValue = strValue.substring(0, 2) + "/" + strValue.substring(2, 4) + "/" + strValue.substring(4);
            }

            DefaultListModel modelCond = (DefaultListModel) lstFiltriCond.getModel();
            javax.swing.table.DefaultTableModel tblMdl = (javax.swing.table.DefaultTableModel)tblFiltri.getModel();
            tblMdl.addRow(new Object[] { (java.lang.String)_OBJFIELDS[ID_LSTFILTRIFLDS][0],
                                         (java.lang.String)modelCond.elementAt(ID_LSTFILTRICOND),
                                         (java.lang.String)strValue } );

            if(tblFiltri.getSelectedRow()<=0)
                tblFiltri.setRowSelectionInterval(0, 0);
            txtFiltro.setText("");
            lbl1.setText("");
            lbl2.setText("");
            lstOp.requestFocus();
            evt.consume();
            //lstFiltriFlds.requestFocus();
        }*/
    }//GEN-LAST:event_txtFiltroKeyPressed

    private void lstOrdinaFldsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstOrdinaFldsKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER)
        {
            DefaultListModel lstMdl = (DefaultListModel) lstOrdinaFlds.getModel();
            int iLstSel = lstOrdinaFlds.getSelectedIndex();
            javax.swing.table.DefaultTableModel tblMdl = (javax.swing.table.DefaultTableModel)tblOrdina.getModel();
            tblMdl.addRow(new Object[] { (java.lang.String)lstMdl.elementAt(iLstSel) } );
            lstMdl.remove(iLstSel);
            if(tblOrdina.getSelectedRow()<=0)
                tblOrdina.setRowSelectionInterval(0, 0);
            lstOrdinaFlds.setSelectedIndex(0);
        }
    }//GEN-LAST:event_lstOrdinaFldsKeyPressed

    private void tblFiltriKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblFiltriKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE)
        {
            int iRow = tblFiltri.getSelectedRow();
            if(iRow==-1) return; // Se non ci sono linee selezionate ritorno
            javax.swing.table.DefaultTableModel tblMdl = (javax.swing.table.DefaultTableModel)tblFiltri.getModel();
            tblMdl.removeRow(iRow);
            if(tblMdl.getRowCount()<=0)
            {
                lstOp.requestFocus();
                lstOp.setSelectedIndex(0);
            } else if(iRow>0) {
                tblFiltri.setRowSelectionInterval(iRow-1, iRow-1);
            } else if(iRow==0) {
                tblFiltri.setRowSelectionInterval(0, 0);
            }
        } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER)
        {
            evt.consume();
            lstOrdinaFlds.requestFocus();
        }
    }//GEN-LAST:event_tblFiltriKeyPressed

    private void tblOrdinaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblOrdinaKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE)
        {
            int iRow = tblOrdina.getSelectedRow();
            if(iRow==-1) return; // Se non ci sono linee selezionate ritorno
            javax.swing.table.DefaultTableModel tblMdl = (javax.swing.table.DefaultTableModel)tblOrdina.getModel();
            DefaultListModel lstMdl = (DefaultListModel) lstOrdinaFlds.getModel();
            lstMdl.addElement( tblMdl.getValueAt(iRow, 0) );
            tblMdl.removeRow(iRow);
            if(tblMdl.getRowCount()<=0)
            {
                lstOrdinaFlds.requestFocus();
                lstOrdinaFlds.setSelectedIndex(0);
            } else if(iRow>0) {
                tblOrdina.setRowSelectionInterval(iRow-1, iRow-1);
            } else if(iRow==0)
            {
                tblOrdina.setRowSelectionInterval(0, 0);
            }
        } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER)
        {
            evt.consume();
            txtMaxRecord.requestFocus();
        }
    }//GEN-LAST:event_tblOrdinaKeyPressed

    
    private void butPrinterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butPrinterMouseClicked
        // TODO add your handling code here
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
            /*our.gui.utils.sqlMap.startTransaction();
            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();*/
            Object[] objWorkData = USE_CUSTOM_MODEL("PRINT");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butPrinterMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                jprint = JasperFillManager.fillReport(jreport, parameters, our.gui.utils.connection);
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butPrinterMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
            //our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            JasperPrintManager.printReport(jprint, true);
        } catch (JRException e) {
//        } catch(java.sql.SQLException sqle) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_butPrinterMouseClicked

    private void butPreviewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butPreviewMouseClicked
        // TODO add your handling code here:
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
            /*our.gui.utils.sqlMap.startTransaction();
            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();*/
            Object[] objWorkData = USE_CUSTOM_MODEL("PREVIEW");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    our.gui.utils.MessageBox("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butPreviewMouseClicked", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                jprint = JasperFillManager.fillReport(jreport, parameters, our.gui.utils.connection);
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butPreviewMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
            //our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            JasperViewer jview = new JasperViewer(jprint);
            JDialog dialog = new JDialog(this, true);
            dialog.setContentPane(jview.getContentPane());
            dialog.setSize(jview.getSize());
            dialog.setTitle("Anteprima di stampa");
            dialog.setVisible(true);
        } catch (JRException e) {
//        } catch(java.sql.SQLException sqle) {
        } catch (Exception e) {
            e.printStackTrace();
        }

    }//GEN-LAST:event_butPreviewMouseClicked

    private void butPDFMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butPDFMouseClicked
        // TODO add your handling code here:
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
//            our.gui.utils.sqlMap.startTransaction();
//            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();
            Object[] objWorkData = USE_CUSTOM_MODEL("PDF");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butPDFMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                jprint = JasperFillManager.fillReport(jreport, parameters, our.gui.utils.connection);
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butPDFrMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
            //our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            String strFile = askUserForFilename("PDF File", "pdf");
            if(strFile!=null) JasperExportManager.exportReportToPdfFile(jprint, strFile);
        } catch (JRException e) {
        //} catch(java.sql.SQLException sqle) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_butPDFMouseClicked

    private void butExcelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butExcelMouseClicked
        // TODO add your handling code here:
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
//            our.gui.utils.sqlMap.startTransaction();
//            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();
            Object[] objWorkData = USE_CUSTOM_MODEL("EXCEL");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butExcelMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                File fTmp = null;
                try {
                    fTmp = File.createTempFile("jreport2xls", ".jreport");
                    jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                    JasperFillManager.fillReportToFile(jreport, fTmp.getAbsolutePath(), parameters, our.gui.utils.connection);
                    jprint = (JasperPrint)JRLoader.loadObject(fTmp);
                    fTmp.delete();
                } catch(IOException ioe) { }
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butExcelrMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
//            our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            String strFile = askUserForFilename("XLS File", "xls");
            if(strFile!=null)
            {
                JRXlsExporter exporter = new JRXlsExporter();
                exporter.setParameter(JRXlsExporterParameter.IS_FONT_SIZE_FIX_ENABLED, Boolean.TRUE);
                exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
                exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
                exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
                exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFile);
                exporter.exportReport();
            }
        } catch (JRException e) {
            javax.swing.JOptionPane.showMessageDialog(this, e, "ERRORE", javax.swing.JOptionPane.ERROR_MESSAGE);
            our.gui.utils.logger.log(Level.SEVERE, e.toString());
/*        } catch(java.sql.SQLException e) {
            javax.swing.JOptionPane.showMessageDialog(this, e, "ERRORE", javax.swing.JOptionPane.ERROR_MESSAGE);
            our.gui.utils.logger.log(Level.SEVERE, e.toString());*/
        } catch(Exception e) {
            javax.swing.JOptionPane.showMessageDialog(this, e, "ERRORE", javax.swing.JOptionPane.ERROR_MESSAGE);
            our.gui.utils.logger.log(Level.SEVERE, e.toString());
        }
    }//GEN-LAST:event_butExcelMouseClicked

    private void butCsvMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butCsvMouseClicked
        // TODO add your handling code here:
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
//            our.gui.utils.sqlMap.startTransaction();
//            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();
            Object[] objWorkData = USE_CUSTOM_MODEL("CSV");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butCsvMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                File fTmp = null;
                try {
                    fTmp = File.createTempFile("jreport2csv", ".jreport");
                    jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                    JasperFillManager.fillReportToFile(jreport, fTmp.getAbsolutePath(), parameters, our.gui.utils.connection);
                    jprint = (JasperPrint)JRLoader.loadObject(fTmp);
                    fTmp.delete();
                } catch(IOException ioe) { }
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butCsvMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
//            our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            String strFile = askUserForFilename("CSV File", "csv");
            if(strFile!=null)
            {
                JRCsvExporter exporter = new JRCsvExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFile);
                exporter.exportReport();
            }
        } catch (JRException e) {
//        } catch(java.sql.SQLException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_butCsvMouseClicked

private void butHTMLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butHTMLMouseClicked
// TODO add your handling code here:
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
//            our.gui.utils.sqlMap.startTransaction();
//            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();
            Object[] objWorkData = USE_CUSTOM_MODEL("HTML");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butHTMLMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                jprint = JasperFillManager.fillReport(jreport, parameters, our.gui.utils.connection);
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butHTMLrMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
//            our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            String strFile = askUserForFilename("HTML File", "html");
            if(strFile!=null) JasperExportManager.exportReportToHtmlFile(jprint, strFile);
        } catch (JRException e) {
//        } catch(java.sql.SQLException sqle) {
        } catch (Exception e) {
            e.printStackTrace();
        }
}//GEN-LAST:event_butHTMLMouseClicked

private void butRTFMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butRTFMouseClicked
// TODO add your handling code here:
    setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JasperReport jreport = null;
        JasperPrint  jprint = null;
        try {
//            our.gui.utils.sqlMap.startTransaction();
//            Connection conn = our.gui.utils.sqlMap.getCurrentConnection();
            Object[] objWorkData = USE_CUSTOM_MODEL("RTF");
            if(objWorkData==null)
            {
                String strQuery = "SELECT ";
                String strFile;
                for(int i=0; i<_OBJFIELDS.length; i++)
                {
                    strQuery+=_OBJFIELDS[i][1] + ", ";
                }
                strQuery = strQuery.substring(0, strQuery.length()-2);
                strQuery += " FROM " + this._TABLENAME + buildQuery();
                // Questa parte viene eseguita quando l'utente usa la query standard e il modello standard
                if( (strFile=buildPrintModel(strQuery)) == null)
                {
                    System.out.println("Non sono riuscito a creare il modello per la stampa/esportazione in ourPrint::butRTFMouseClicked\n");
                    System.exit(1);
                }
                String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                Map parameters = new HashMap();
                parameters.put("ReportTitle", getTitle());
                parameters.put("DataFile", sdf.format(cal.getTime()));
                File fTmp = null;
                try {
                    fTmp = File.createTempFile("jreport2rtf", ".jreport");
                    jreport = JasperCompileManager.compileReport(strFile); // Creo il report
                    JasperFillManager.fillReportToFile(jreport, fTmp.getAbsolutePath(), parameters, our.gui.utils.connection);
                    jprint = (JasperPrint)JRLoader.loadObject(fTmp);
                    fTmp.delete();
                } catch(IOException ioe) { }
            } else {
                if(objWorkData.length!=2)
                {
                    System.out.println("Numero di parametri errato! ourPrint::butRTFrMouseClicked\n");
                    System.exit(1);
                }
                //jreport = (JasperReport)objWorkData[1];
                jprint  = (JasperPrint)objWorkData[1];
            }
//            our.gui.utils.sqlMap.endTransaction();
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            String strFile = askUserForFilename("RTF File", "rtf");
            if(strFile!=null)
            {
                
                JRRtfExporter exporter = new JRRtfExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFile);
                exporter.exportReport();
            }
        } catch (JRException e) {
//        } catch(java.sql.SQLException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
}//GEN-LAST:event_butRTFMouseClicked

private void lstFiltriFldsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstFiltriFldsFocusLost
    // TODO add your handling code here:
    ID_LSTFILTRIFLDS = lstFiltriFlds.getSelectedIndex();
    java.awt.Rectangle rFiltro = lstFiltriCond.getBounds();
    java.awt.Component cmp = evt.getOppositeComponent();
    if(cmp!=null)
    {
        java.awt.Rectangle rOpp    = cmp.getBounds();
        if( (rFiltro.x==rOpp.x) && (rFiltro.y==rOpp.y) )
            lbl1.setText((java.lang.String)lstFiltriFlds.getSelectedValue());
    }
    lstFiltriFlds.clearSelection();
}//GEN-LAST:event_lstFiltriFldsFocusLost

private void lstFiltriFldsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstFiltriFldsFocusGained
    // TODO add your handling code here:
    lstFiltriFlds.setSelectedIndex(ID_LSTFILTRIFLDS);
}//GEN-LAST:event_lstFiltriFldsFocusGained

private void lstFiltriCondFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstFiltriCondFocusLost
    // TODO add your handling code here:
    ID_LSTFILTRICOND = lstFiltriCond.getSelectedIndex();
    java.awt.Rectangle rFiltro = txtFiltro.getBounds();
    java.awt.Component cmp = evt.getOppositeComponent();
    if(cmp!=null)
    {
        java.awt.Rectangle rOpp    = cmp.getBounds();
        if( (rFiltro.x==rOpp.x) && (rFiltro.y==rOpp.y) )
            lbl2.setText((java.lang.String)lstFiltriCond.getSelectedValue());
    }
    lstFiltriCond.clearSelection();
}//GEN-LAST:event_lstFiltriCondFocusLost

private void lstFiltriCondFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstFiltriCondFocusGained
    // TODO add your handling code here:
    lstFiltriCond.setSelectedIndex(ID_LSTFILTRICOND);
}//GEN-LAST:event_lstFiltriCondFocusGained

private void tblFiltriFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblFiltriFocusLost
    // TODO add your handling code here:
    ID_IDTABLE = tblFiltri.getSelectedRow();
    tblFiltri.clearSelection();
}//GEN-LAST:event_tblFiltriFocusLost

private void tblFiltriFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblFiltriFocusGained
    // TODO add your handling code here:
    if(ID_IDTABLE>=0 && tblFiltri.getRowCount()>0) tblFiltri.setRowSelectionInterval(ID_IDTABLE, ID_IDTABLE);
}//GEN-LAST:event_tblFiltriFocusGained

private void lstOrdinaFldsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstOrdinaFldsFocusLost
    // TODO add your handling code here:
    ID_LSTORD = lstOrdinaFlds.getSelectedIndex();
    lstOrdinaFlds.clearSelection();
}//GEN-LAST:event_lstOrdinaFldsFocusLost

private void lstOrdinaFldsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstOrdinaFldsFocusGained
    // TODO add your handling code here:
    int nSize = lstOrdinaFlds.getModel().getSize();
    if(nSize>0) lstOrdinaFlds.setSelectedIndex(ID_LSTORD);
}//GEN-LAST:event_lstOrdinaFldsFocusGained

private void tblOrdinaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblOrdinaFocusLost
    // TODO add your handling code here:
    ID_LSTORDSEL = tblOrdina.getSelectedRow();
    tblOrdina.clearSelection();
}//GEN-LAST:event_tblOrdinaFocusLost

private void tblOrdinaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblOrdinaFocusGained
    // TODO add your handling code here:
    if(ID_LSTORDSEL>=0 && tblOrdina.getRowCount()>0) tblOrdina.setRowSelectionInterval(ID_LSTORDSEL, ID_LSTORDSEL);
}//GEN-LAST:event_tblOrdinaFocusGained

private void lstFiltriCondMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstFiltriCondMouseClicked
    // TODO add your handling code here:
    javax.swing.JList lst = (javax.swing.JList)evt.getSource();
    ID_LSTFILTRICOND = lst.locationToIndex(evt.getPoint());
    lst.setSelectedIndex(ID_LSTFILTRICOND);
}//GEN-LAST:event_lstFiltriCondMouseClicked

private void lstFiltriFldsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstFiltriFldsMouseClicked
    // TODO add your handling code here:
    javax.swing.JList lst = (javax.swing.JList)evt.getSource();
    ID_LSTFILTRIFLDS = lst.locationToIndex(evt.getPoint());
    lst.setSelectedIndex(ID_LSTFILTRIFLDS);
}//GEN-LAST:event_lstFiltriFldsMouseClicked

private void lstOpFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstOpFocusGained
    // TODO add your handling code here:
    lstOp.setSelectedIndex(ID_LSTORD);
}//GEN-LAST:event_lstOpFocusGained

private void lstOpFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lstOpFocusLost
    // TODO add your handling code here:
    ID_LSTOP = lstOp.getSelectedIndex();
    lstOp.clearSelection();
}//GEN-LAST:event_lstOpFocusLost

private void lstOpKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstOpKeyPressed
    // TODO add your handling code here:
    if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) && (!txtFiltro.getText().isEmpty()) )
    {
        int iType = (java.lang.Integer)_OBJFIELDS[ID_LSTFILTRIFLDS][2];
        String strValue = txtFiltro.getText();
        if(iType==our.gui.ourTextField.TYPE_DATA)
        {
            strValue = our.gui.utils.isValidDate(strValue);
            if(strValue==null)
            {
                our.gui.utils.MessageBox("Hai inserito una data non valida!", JOptionPane.ERROR_MESSAGE);
                txtFiltro.requestFocus();
                evt.consume();
                return;
            }
            strValue = strValue.substring(0, 2) + "/" + strValue.substring(2, 4) + "/" + strValue.substring(4);
        }
        DefaultListModel modelCond = (DefaultListModel) lstFiltriCond.getModel();
        String strOp = " AND ";
        if(lstOp.getSelectedIndex()==1) strOp = " OR ";
        javax.swing.table.DefaultTableModel tblMdl = (javax.swing.table.DefaultTableModel)tblFiltri.getModel();
        tblMdl.addRow(new Object[] { (java.lang.String)_OBJFIELDS[ID_LSTFILTRIFLDS][0],
                                     (java.lang.String)modelCond.elementAt(ID_LSTFILTRICOND),
                                     (java.lang.String)strValue,
                                     (java.lang.String)strOp } );

        if(tblFiltri.getSelectedRow()<=0)
            tblFiltri.setRowSelectionInterval(0, 0);
        txtFiltro.setText("");
        lbl1.setText("");
        lbl2.setText("");
    } else if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) && (txtFiltro.getText().isEmpty()) ) {
        our.gui.utils.MessageBox("Per aggiungere una condizione devi aggiungere un valore!", JOptionPane.ERROR_MESSAGE);
        evt.consume();
        txtFiltro.requestFocus();
    }
}//GEN-LAST:event_lstOpKeyPressed

private void lstOrdinaFldsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstOrdinaFldsMouseClicked
    // TODO add your handling code here:
    javax.swing.JList lst = (javax.swing.JList)evt.getSource();
    ID_LSTORD = lst.locationToIndex(evt.getPoint());
    lst.setSelectedIndex(ID_LSTORD);
}//GEN-LAST:event_lstOrdinaFldsMouseClicked

private void tblFiltriMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblFiltriMouseClicked
    // TODO add your handling code here:
    javax.swing.JTable tbl = (javax.swing.JTable)evt.getSource();
    ID_IDTABLE = tbl.rowAtPoint(evt.getPoint());
    tblFiltri.setRowSelectionInterval(ID_IDTABLE, ID_IDTABLE);
}//GEN-LAST:event_tblFiltriMouseClicked

private void tblOrdinaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblOrdinaMouseClicked
    // TODO add your handling code here:
    javax.swing.JTable tbl = (javax.swing.JTable)evt.getSource();
    ID_LSTORDSEL = tbl.rowAtPoint(evt.getPoint());
    tblOrdina.setRowSelectionInterval(ID_LSTORDSEL, ID_LSTORDSEL);
}//GEN-LAST:event_tblOrdinaMouseClicked

    private String askUserForFilename(String sDesc, String sExt)
    {
        String strExt = null;
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new MyFilter(sDesc, new String( sExt )));
        fc.showSaveDialog(this);
        File selFile = fc.getSelectedFile();
        if(selFile!=null)
        {
            strExt = selFile.getAbsolutePath().substring(selFile.getAbsolutePath().length()-4);
            if(!strExt.equalsIgnoreCase(sExt))
                strExt = selFile.getAbsolutePath() + "." + sExt;
            else
                strExt = selFile.getAbsolutePath();
        }
        return strExt;
    }

    class MyFilter extends javax.swing.filechooser.FileFilter {
        String description;

        String extensions[];

        public MyFilter(String description, String extension) {
            this(description, new String[] { extension });
        }

        public MyFilter(String description, String extensions[]) {
            if (description == null) {
                this.description = extensions[0];
            } else {
                this.description = description;
            }
            this.extensions = (String[]) extensions.clone();
            toLower(this.extensions);
        }

        private void toLower(String array[]) {
            for (int i = 0, n = array.length; i < n; i++) {
                array[i] = array[i].toLowerCase();
            }
        }

        public String getDescription() {
            return description;
        }

        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else {
                String path = file.getAbsolutePath().toLowerCase();
                for (int i = 0, n = extensions.length; i < n; i++) {
                    String extension = extensions[i];
                    if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
                        return true;
                    }
                }
            }
            return false;
        }
    }


    /**
     * Nella cartella tmp crea il modello che verrà utilizzato in fase di stampa, creazione pdf, xls, rtf ecc ecc
     * @param  strQuery è la query che verrà inserita all'interno dell'xml base
     * @return Il nome del file contenente il modello, null altrimenti
     */
    private String buildPrintModel(String strQuery)
    {
        InputStream is = null;
        BufferedReader br = null;
        BufferedWriter out = null;
        String line;
        try {
            // Creo un file temporaneo
            File fTmp = File.createTempFile("printmodel", ".jrxml");
            out = new BufferedWriter(new FileWriter(fTmp));
            is = this.getClass().getResourceAsStream("/stampe/modelli/base.jrxml");
            br = new BufferedReader(new InputStreamReader(is));
            while(null!=(line=br.readLine()))
            {
                //if(line.indexOf("${QUERY}")>=0)
                if(line.indexOf("<queryString>")>=0)
                {
                    // Creo la linea che contiene la query
                    line = "<queryString><![CDATA[" + strQuery + "]]></queryString>\n";
                    out.write(line);
                } else if(line.indexOf("${FIELDS}")>=0)
                {
                    // Creo la linea che contiene i parametri
                    for(int i=0; i<_OBJFIELDS.length; i++)
                    {
                        line="<field name=\"" + _OBJFIELDS[i][1] + "\" class=\"";
                        if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_CODNUM)
                            line += "java.lang.Integer\"></field>";
                        else if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_ALFANUM)
                            line += "java.lang.String\"></field>";
                        else if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_NUMERIC)
                            line += "java.lang.Double\"></field>";
                        else {
                            System.out.println("Errore di definizione di campo in ourPrint.java::buildPrintModule");
                            throw new Exception("Errore di definizione di campo in ourPrint.java::buildPrintModule");
                        }
                        out.write(line + "\n");                                 
                    }
                } else if(line.indexOf("${PAGEHEADER}")>=0)
                {
                    // Creo l'header
                    for(int i=0; i<_OBJFIELDS.length; i++)
                    {
                        line = "<staticText>\n<reportElement x=\"" + _OBJFIELDS[i][3];
                        line += "\" y=\"5\" width=\"" + _OBJFIELDS[i][4] + "\" height=\"10\" forecolor=\"white\"";
                        line += " backcolor=\"#333333\" mode=\"Opaque\" style=\"Sans_Bold\"/>\n";
                        line += "<textElement textAlignment=\"Center\"/>\n<text>" + _OBJFIELDS[i][0] + "</text>\n</staticText>\n";
                        out.write(line + "\n");                                 
                    }
                } else if(line.indexOf("{$DETAILS}")>=0)
                {
                    for(int i=0; i<_OBJFIELDS.length; i++)
                    {
                        line = "<textField>\n<reportElement x=\"" + _OBJFIELDS[i][3] + "\" y=\"4\" width=\"" + _OBJFIELDS[i][4] + "\" height=\"10\"/>\n";
                        line += "<textElement textAlignment=\"Left\"/>\n";
                        if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_CODNUM)
                            line += "<textFieldExpression class=\"java.lang.Integer\">\n";
                        else if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_ALFANUM)
                            line += "<textFieldExpression class=\"java.lang.String\">\n";
                        else if((java.lang.Integer)_OBJFIELDS[i][2] == our.gui.ourTextField.TYPE_NUMERIC)
                            line += "<textFieldExpression class=\"java.lang.Double\">\n";
                        else {
                            System.out.println("Errore di definizione di campo in ourPrint.java::buildPrintModule");
                            System.exit(1);
                        }
                        line += "$F{" + _OBJFIELDS[i][1] + "}\n</textFieldExpression>\n</textField>\n";
                        out.write(line + "\n");
                    }
                } else {
                   out.write(line + "\n");
                }
            }
            out.close();
            line = fTmp.getAbsolutePath();
        } catch(Exception e) {
            our.gui.utils.logger.log(Level.SEVERE, e.toString());
            line = null;
        }
        return line;
    }
    
    protected String buildQuery()
    {
        String strQuery = "";
        DefaultTableModel tblMdl = (DefaultTableModel) tblFiltri.getModel();
        int iRow = tblMdl.getRowCount();
        for(int i=0; i<iRow; i++)
        {
            String strVal = (java.lang.String)tblMdl.getValueAt(i, 2);
            int iType = (java.lang.Integer)_OBJFIELDS[ID_LSTFILTRIFLDS][2]; // Leggo il tipo di oggetto
            if(iType==our.gui.ourTextField.TYPE_DATA)
            {
                String strDay = strVal.substring(0, 2);
                String strMon = strVal.substring(3, 5);
                String strYea = strVal.substring(6);
                strVal = "'" + strYea + "-" + strMon + "-" + strDay + "'";
            }
            String strCond = (java.lang.String)tblMdl.getValueAt(i, 1);
            //if(strQuery.length()>0) strQuery += " AND ";
            if(strQuery.length()>0) strQuery += (java.lang.String)tblMdl.getValueAt(i - 1, 3);
            strQuery += FieldToMysql( (java.lang.String)tblMdl.getValueAt(i, 0) );
            if(strCond.indexOf("Inizia")>=0)
            {
                strQuery += " LIKE '" + strVal + "%'";
            } else if(strCond.indexOf("Finisce")>=0) {
                strQuery += " LIKE '%" + strVal + "'";
            } else if(strCond.indexOf("Contiene")>=0) {
                strQuery += " LIKE '%" + strVal + "%'";
            } else if(strCond.indexOf("Uguale a")>=0) {
                strQuery += "='" + strVal + "'";
            } else {
                strQuery += (java.lang.String)tblMdl.getValueAt(i, 1);
                strQuery += strVal;
            }
        }
        tblMdl = (DefaultTableModel) tblOrdina.getModel();
        iRow = tblMdl.getRowCount();
        if(iRow>0) strQuery += " ORDER BY ";
        for(int i=0; i<iRow; i++)
            strQuery += FieldToMysql( (java.lang.String)tblMdl.getValueAt(i, 0) ) + ", ";
        if(iRow>0) strQuery = strQuery.substring(0, strQuery.length()-2);
        if(strQuery.length()>0 && (strQuery.indexOf("ORDER")>=2 || strQuery.indexOf("ORDER")<0)) strQuery = " WHERE " + strQuery;
        if(!txtMaxRecord.getText().isEmpty())
            strQuery += " LIMIT " + txtMaxRecord.getText();
        return strQuery;
    }

    /**
     * Cerca nella struttura iniziale il valore del campo passato in strField e lo converte nel corrispondente MySQL
     * @param strField Il campo da convertire: quello che solitamente è visualizzato sulla form
     * @return Il nome del campo corrispondente nel database, null altrimenti
     */
    private String FieldToMysql(String strField)
    {
        for(int i=0; i<_OBJFIELDS.length; i++)
        {
            if(_OBJFIELDS[i][0].toString().equalsIgnoreCase(strField))
                return (java.lang.String)_OBJFIELDS[i][1].toString();
        }
        System.out.println("Hai passato un campo che non esiste!");
        System.exit(1);
        return null;
    }

    /**
     * Cerca nella struttura iniziale il valore del campo passato in strField e ritorna la tipologia (NUMERICO, ALFANUMERICO)
     * @param strField Il campo da convertire: quello che solitamente è visualizzato sulla form
     * @return Il tipo di dato
     */
    private int FieldToType(String strField)
    {
        for(int i=0; i<_OBJFIELDS.length; i++)
        {
            if(_OBJFIELDS[i][0].toString().equalsIgnoreCase(strField))
                return (java.lang.Integer)_OBJFIELDS[i][2];
        }
        System.out.println("Hai passato un campo che non esiste!");
        System.exit(1);
        return -1;
    }

    // Inner class
    class FXAction extends AbstractAction {
        private String key;
        private CustomEvent customEvent;

        public FXAction(String key, CustomEvent customEvent)
        {
            this.key = key;
            this.customEvent = customEvent;
        }

        public void actionPerformed(ActionEvent e) {
            if(customEvent!=null)
            {
                customEvent.esegui(key);
            }
        }
    }

    // Inner class
    class CustomEvent {
        public void esegui(String key)
        {
            if(key.equalsIgnoreCase("ESC"))
            {
                dispose();
            }
            if(key.equalsIgnoreCase("DOWN"))
            {
                KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                kfm.focusNextComponent();
            }
            if(key.equalsIgnoreCase("UP"))
            {
                KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                kfm.focusPreviousComponent();
            }
            if(key.equalsIgnoreCase("F1")) butPreviewMouseClicked(null);
            if(key.equalsIgnoreCase("F2")) butPrinterMouseClicked(null);
            if(key.equalsIgnoreCase("F3")) butExcelMouseClicked(null);
            if(key.equalsIgnoreCase("F4")) butPDFMouseClicked(null);
            if(key.equalsIgnoreCase("F5")) butCsvMouseClicked(null);
            if(key.equalsIgnoreCase("F6")) butHTMLMouseClicked(null);
            if(key.equalsIgnoreCase("F7")) butRTFMouseClicked(null);
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private our.gui.ourButton butCsv;
    private our.gui.ourButton butExcel;
    private our.gui.ourButton butHTML;
    private our.gui.ourButton butPDF;
    private our.gui.ourButton butPreview;
    private our.gui.ourButton butPrinter;
    private our.gui.ourButton butRTF;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private our.gui.ourLabel lbl1;
    private our.gui.ourLabel lbl2;
    private our.gui.ourList lstFiltriCond;
    private our.gui.ourList lstFiltriFlds;
    private our.gui.ourList lstOp;
    private our.gui.ourList lstOrdinaFlds;
    private javax.swing.JPanel panelToolbar;
    private javax.swing.JPanel pnlFiltri;
    private javax.swing.JPanel pnlOperatore;
    private javax.swing.JPanel pnlOrdinamento;
    private our.gui.ourTable tblFiltri;
    private our.gui.ourTable tblOrdina;
    private our.gui.ourTextField txtFiltro;
    private our.gui.ourTextField txtMaxRecord;
    // End of variables declaration//GEN-END:variables

}
